package com.eling.elcms.travel.service.impl;

import com.eling.elcms.core.AppContext;
import com.eling.elcms.core.service.impl.GenericManagerImpl;
import com.eling.elcms.core.util.PropertyUtils;
import com.eling.elcms.ordermanager.model.Attendant;
import com.eling.elcms.ordermanager.service.IAttendantManager;
import com.eling.elcms.system.model.CommonUser;
import com.eling.elcms.system.service.ICommonUserManager;
import com.eling.elcms.travel.dao.IApprovalDefineItemDao;
import com.eling.elcms.travel.model.ApprovalDefine;
import com.eling.elcms.travel.model.ApprovalDefineItem;
import com.eling.elcms.travel.model.view.ApprovalDefineItemView;
import com.eling.elcms.travel.service.IApprovalDefineItemService;
import com.eling.elcms.travel.service.IApprovalDefineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ApprovalDefineItemServiceImpl extends GenericManagerImpl<ApprovalDefineItem, Long> implements IApprovalDefineItemService{
	@Autowired
	IApprovalDefineItemDao approvalDefineItemDao;
	@Autowired
	private IApprovalDefineService approvalDefineService;
	@Autowired
	private IAttendantManager attendantManager;
	@Autowired
	private ICommonUserManager commonUserManager;
	@Autowired
	public void setDao(IApprovalDefineItemDao dao) {
		this.dao = dao;
	}

	@Override
	public ApprovalDefineItem saveInDefine(ApprovalDefineItem approvalDefineItem) {
		approvalDefineItem = save(approvalDefineItem);
		ApprovalDefine app  =approvalDefineService.get(approvalDefineItem.getApprovalDefine().getPkApprovalDefine()) ;
		app.setSetupTime(new Date());
		app.setUser(AppContext.curUser());
		approvalDefineService.save(app);
		return approvalDefineItem;
	}

	@Override
	public List<ApprovalDefineItemView> queryAll(ApprovalDefineItem cond) {
//		String fetchProperties = PropertyUtils.getProperty(cond, "fetchProperties");
		PropertyUtils.setProperty(cond, "fetchProperties",null);
		List<ApprovalDefineItem> list = query(cond);
		List<Long> pklist = new ArrayList<Long>();
		for(ApprovalDefineItem adi : list){
			pklist.add(adi.getPkApprovalDefineItem());
		}
		return approvalDefineItemDao.queryItem(pklist);
	}

	@Override
	public ApprovalDefineItem saveAll(ApprovalDefineItem approvalDefineItem,
			Long pkPersonalInfo) {
		Attendant att =new Attendant();
		PropertyUtils.setProperty(att, "personalInfo.pkPersonalInfo", pkPersonalInfo);
		att = attendantManager.query(att).get(0);
		CommonUser cu = commonUserManager.get(att.getCommonUser().getPkUser());
		approvalDefineItem.setApprovalUser(cu);
		approvalDefineItem = save(approvalDefineItem);
		ApprovalDefine app  =approvalDefineService.get(approvalDefineItem.getApprovalDefine().getPkApprovalDefine()) ;
		app.setSetupTime(new Date());
		app.setUser(AppContext.curUser());
		approvalDefineService.save(app);
		return approvalDefineItem;
	}
	
}
